//*********************************************************
//
//    Copyright (c) Microsoft. All rights reserved.
//    This code is licensed under the Apache License, Version 2.0.
//    THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
//    ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
//    IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
//    PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
//
//*********************************************************

namespace Microsoft.Research.eResearch.Subscriber.Wcf
{
    using System;
    using System.ServiceModel;
    using Microsoft.Research.eResearch.Blackboard.Common;

    /// <summary>
    /// Provides an extension that the WCF ServiceHost can expose to allow the <see cref="WcfNotificationMessageService"/>
    /// to fire events (from a WCF-created thread) when a new blackboard message is received.
    /// </summary>
    public class NotificationMessageReceiverExtension : IExtension<ServiceHostBase>
    {
        /// <summary>
        /// Method to be executed whenever message is received from blackboard.
        /// </summary>
        private Action<BlackboardMessage> onBlackboardMessageReceived;

        /// <summary>
        /// Initializes a new instance of the <see cref="NotificationMessageReceiverExtension"/> class.
        /// </summary>
        /// <param name="onBlackboardMessageReceived">The method to call when a new blackboard message is received.</param>
        public NotificationMessageReceiverExtension(Action<BlackboardMessage> onBlackboardMessageReceived)
        {
            this.onBlackboardMessageReceived = onBlackboardMessageReceived;
        } 

        /// <summary>
        /// Enables an extension object to find out when it has been aggregated. Called when the extension 
        /// is added to the <see cref="P:System.ServiceModel.IExtensibleObject`1.Extensions"/> property.
        /// </summary>
        /// <param name="owner">The extensible object that aggregates this extension.</param>
        public void Attach(ServiceHostBase owner)
        {
        } 

        /// <summary>
        /// Enables an object to find out when it is no longer aggregated. Called when an extension is removed 
        /// from the <see cref="P:System.ServiceModel.IExtensibleObject`1.Extensions"/> property.
        /// </summary>
        /// <param name="owner">The extensible object that aggregates this extension.</param>
        public void Detach(ServiceHostBase owner)
        {
        } 

        /// <summary>
        /// Notifies the subscriber of a new blackboard message.
        /// </summary>
        /// <param name="message">The new blackboard message.</param>
        public void Notify(BlackboardMessage message)
        {
            onBlackboardMessageReceived(message);
        } 
    }
}
